import React, { Component } from 'react'
import axios from '../../utils/request'
import { message } from 'antd';

export default class Login extends Component {
    state = {
        username: '',
        password: ''
    }

    username(e) {
        this.setState({
            username: e.target.value,
        });
    }
    password(e) {
        this.setState({
            password: e.target.value,
        });
    }
    //登录
    toLogin = () => {
        axios({
            url: '/api/login',
            method: 'post',
            data: {
                username: this.state.username,
                password: this.state.password
            }
        }).then(res => {
            // console.log(res);
            if (res.data.code === 1) {
                window.localStorage.setItem('token', res.data.token)
                this.props.history.push('/app/re')
                //同步姓名和头像
                localStorage.setItem('username', res.data.data.username)
                localStorage.setItem('img', res.data.data.img)
                // alert(res.data.msg)
                message.success(res.data.msg);
            } else {
                // alert(res.data.msg)
                message.error(res.data.msg);
            }
        })
    }

    //注册
    register() {
        axios({
            url: '/api/register',
            method: 'post',
            data: {
                username: this.state.username,
                password: this.state.password
            }
        }).then(res => {
            // console.log(res.data.data);
            if (res.data.code === 2) {
                message.warning(res.data.msg);
            } else {
                message.success(res.data.msg);
            }
        })
    }


    render() {
        return (
            <div className="public1">
                <div className='login'>
                    <p>
                        <input type="text" placeholder="请输入用户名" onChange={(e) => { this.username(e) }} />
                    </p>
                    <p>
                        <input type="password" placeholder="请输入密码" onChange={(e) => { this.password(e) }} />
                    </p>
                    <div className="but">
                        <button onClick={() => { this.toLogin() }}>登录</button>
                        <button onClick={() => { this.register() }}>注册</button>
                    </div>
                </div>
            </div>
        )
    }
}